package com.itic.appbase.framework.interceptor;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.itic.appbase.applications.sys.user.persistence.model.SysUser;
import com.itic.appbase.applications.sys.user.service.SysUserService;
import com.itic.appbase.framework.annotation.CheckLogin;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mobile.base.BaseMobile;

public class APPInterceptor extends BaseMobile implements HandlerInterceptor{
	@Autowired
	private SysUserService sysUserService;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		boolean flag = true;
		Class<?> clazz = handler.getClass();
		if(handler.getClass().isAssignableFrom(HandlerMethod.class)) {
			CheckLogin checkLogin = ((HandlerMethod) handler).getMethodAnnotation(CheckLogin.class);
			if(checkLogin!=null) {
				//TODO 添加需要的拦截业务
				String token = request.getParameter("token");//登入的用户token
				String device= request.getParameter("device");//登入的设备标识
				if( StringUtils.isNotBlank(token) && StringHelper.isNotBlank(device) ) {
					SysUser user = sysUserService.getUserByTokenAndDevice(token,device);
					if( null!=user ){
						request.setAttribute(RequestUser, user);
					}else{
						flag = false;
					}
				}else
					flag = false;
			}else 
				flag = true;
			if(!flag) {
				//JSONObject res=new JSONObject();
				Map<String, Object> res = new HashMap<String, Object>();
				res.put(CODE, LOGIN_ERROR_CODE);
				res.put(MSG, LOGIN_ERROR_MSG);
				PrintWriter out = null;
				StringBuffer result = new StringBuffer();
				try {
					response.setContentType("application/json");
					out =response.getWriter();
					result.append("{\""+CODE+"\":\""+LOGIN_ERROR_CODE+"\",\""+MSG+"\":\""+LOGIN_ERROR_MSG+"\"}");
				} catch (Exception e) {
					result.append("{\""+CODE+"\":\""+SERVER_ERROR_CODE+"\",\""+MSG+"\":\""+SERVER_ERROR_MSG+"\"}");
					logException("APPInterceptor", "preHandle", e.toString(),"app端拦截器",e);
				}finally {
					out.println(result.toString());
					out.flush();
					out.close();
				}
			}
		}
		return flag;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}

}
